package io.renren.modules.sys.lucene.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.renren.modules.sys.back.entity.BtJishuInfoEntity;
import io.renren.modules.sys.back.entity.BtRenwuInfoEntity;
import io.renren.modules.sys.back.service.BtJishuInfoService;
import io.renren.modules.sys.back.service.BtRenwuInfoService;
import io.renren.modules.sys.lucene.entity.LuceneDocEntity;
import io.renren.modules.sys.lucene.utils.LuceneRenWuUtils;
import io.renren.modules.sys.lucene.utils.LuceneUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.util.Version;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LuceneRenWuServicImpl {
    @Autowired
    private BtRenwuInfoService btRenwuInfoService;

    public Boolean createIndexDB() throws Exception {
        List<LuceneDocEntity>list = getchanping();

        List<Document> documents =new ArrayList<>();
        for (LuceneDocEntity us:list) {
            Document document = LuceneRenWuUtils.javaBean2Document(us);
            documents.add(document);
        }
        /**
         * IndexWriter将我们的document对象写到硬盘中
         *
         * 参数一：Directory d,写到硬盘中的目录路径是什么
         * 参数二：Analyzer a, 以何种算法来对document中的原始记录表数据进行拆分成词汇表
         * 参数三：MaxFieldLength mfl 最多将文本拆分出多少个词汇
         *
         * */
        IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_43,
                LuceneUtils.getAnalyzer());;
        //IndexWriter indexWriter = new IndexWriter(LuceneUtils.getDirectory(), getAnalyzer(), LuceneUtils.getMaxFieldLength());
        IndexWriter indexWriter = new IndexWriter(LuceneRenWuUtils.getDirectory(), iwConfig);
        //将Document对象通过IndexWriter对象写入索引库中
        for (Document ss:documents)
            indexWriter.addDocument(ss);
        indexWriter.close();
        return true;
    }
    public List<Map<String,Object>> findIndexDB(String para) throws Exception {
        //创建IndexSearcher对象
        IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(LuceneRenWuUtils.getDirectory()));
        //创建QueryParser对象
        String[]stringQuery={para,para};
        //待查找字符串对应的字段
        String[] fields={"name","sammary"};
        //Occur.MUST表示对应字段必须有查询值， Occur.MUST_NOT 表示对应字段必须没有查询值，Occur.SHOULD表示对应字段应该存在查询值（但不是必须）
        BooleanClause.Occur[]occ={BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD};
        Query query = MultiFieldQueryParser.parse(Version.LUCENE_43,stringQuery,fields,occ,LuceneRenWuUtils.getAnalyzer());
        TopDocs topDocs = indexSearcher.search(query,5);
        System.out.println("命中数:"+topDocs.totalHits);

        /*QueryParser queryParser = new QueryParser(Version.LUCENE_43, "name", LuceneRenWuUtils.getAnalyzer());
        //给出要查询的关键字
         String keyWords = "电子";
        //创建Query对象来封装关键字
        Query query = queryParser.parse(keyWords);
        //用IndexSearcher对象去索引库中查询符合条件的前100条记录，不足100条记录的以实际为准
        TopDocs topDocs = indexSearcher.search(query, 100);
        System.out.println("命中数:"+topDocs.totalHits);*/
        //获取符合条件的编号
        List<Map<String,Object>> backdata =new ArrayList<>();
        for (int i = 0; i < topDocs.scoreDocs.length; i++) {
            Map<String,Object> tem = new HashMap<>();
            ScoreDoc scoreDoc = topDocs.scoreDocs[i];
            int no = scoreDoc.doc;
            //用indexSearcher对象去索引库中查询编号对应的Document对象
            Document document = indexSearcher.doc(no);
            //将Document对象中的所有属性取出，再封装回JavaBean对象中去
            LuceneDocEntity luceneDocEntity = (LuceneDocEntity) LuceneUtils.Document2JavaBean(document, LuceneDocEntity.class);
            // System.out.println(user);
            tem.put("name",luceneDocEntity.getName());
            tem.put("link","/api/jishu/detail/"+luceneDocEntity.getId());
            if(!luceneDocEntity.getImg().equals("loadfalse")) tem.put("img",luceneDocEntity.getImg());
            String tmp = luceneDocEntity.getSammary();
            if(!tmp.equals("")){
                org.jsoup.nodes.Document doc = Jsoup.parse(tmp);
                Elements subimg = doc.getElementsByClass("infozyao");
                if(subimg!=null&&subimg.size()>0) {
                    tem.put("content",subimg.get(0).childNode(4).outerHtml());
                }
            }
            backdata.add(tem);
        }
        return backdata;
    }
    private List<LuceneDocEntity> getchanping(){
        List<LuceneDocEntity> badate=new ArrayList<>();
        List<BtRenwuInfoEntity> serlist= btRenwuInfoService.selectList(new EntityWrapper<BtRenwuInfoEntity>());
        if(serlist.size()>0){
            for (BtRenwuInfoEntity sb:serlist){
                LuceneDocEntity luceneDocEntity = new LuceneDocEntity();
                luceneDocEntity.setId(sb.getId());
                luceneDocEntity.setName(sb.getName());
                luceneDocEntity.setSammary(sb.getSummer());
                if(sb.getImg()==null){
                    luceneDocEntity.setImg("loadfalse");
                }else
                    luceneDocEntity.setImg(sb.getImg());
                badate.add(luceneDocEntity);
            }
        }
        return badate;
    }
}
